<template>
    <div class="ui-player" :class="{'loading':!canPlay}" v-show="config.status" :style="config.style">
        <video ref="video" 
            @click="play"
            v-if="config.video"
            playsinline="isiPhoneShowPlaysinline" 
            webkit-playsinline 
            x-webkit-airplay="" 
            preload="none" 
            controls="true"
            controlsList="nodownload"
            :muted="!config.voice"
            :src="config.video">
        </video>
    </div>
</template>
<script>
export default {
    name:'ui-player',
    props:{
        config:{
            type:Object,
            default:{
                status:false,
                voice:true,
                video:'',
                style:""
            }
        }
    },
    data(){
        return {
            canPlay:false
        }
    },
    watch:{
        'config.video':function(v,ov){
              this.$nextTick(()=>{
                    this.$refs.video && 
                    this.stop(),this.$refs.video.addEventListener('volumechange',this.mutedChange, false),
                        this.$refs.video.addEventListener('canplay',this.readyPlay,false), this.canPlay = false,this.play()
                })
        }
    },
    mounted(){
        this.$on('PLYAER_CLOSE',()=>{
            this.stop();
        });
        if(location.pathname.indexOf('/video.html') == -1){
            window.addEventListener('scroll',()=>{
                if(this.$refs.video){
                    let rect = this.$refs.video.getBoundingClientRect();
                    if(rect.top < 0 && Math.abs(rect.top) >= rect.height || rect.top >= window.innerHeight){
                        this.stop();
                    }
                }
            });
        }
        
        
    },
    methods:{
        readyPlay(e){
            this.canPlay = true;
            this.play();
        },
        mutedChange(e){
            this.$emit('muted',this.$refs.video.muted)
        },
        play(){
            this.$refs.video && this.$refs.video.play();
        },
        stop(){
            this.$refs.video && this.$refs.video.pause();
        },
        silent(){

        }
    }
}
</script>
<style lang="less">
.ui-player {
    position: absolute;
    left:0;
    right:0;
    margin:auto;
    z-index:99;

    video {
        display: block;
        width:100%;
        height: 100%;
    }

    &.loading {
        &::after {
            content:'';
            position: absolute;
            top:0;
            left:0;
            right:0;
            bottom:0;
            margin:auto;
            width:80px;
            height:80px;
            border:2px solid #fff;
            border-radius: 50%;
            border-bottom-color: transparent;
            animation:loading 1s infinite linear;
        }
    }
}
</style>

